package com.slipper.util;

import com.slipper.core.gson.GsonUtil;
import com.slipper.exception.CommonException;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.ComputerSystem;
import oshi.hardware.HardwareAbstractionLayer;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.*;

public class MachineUtil {
    public static String getIpAddress() {
        try {
            TreeSet<String> treeSet = new TreeSet<>();
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                if (networkInterface.isUp() && !networkInterface.isVirtual() && !networkInterface.isLoopback()) {
                    Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                    while (inetAddresses.hasMoreElements()) {
                        InetAddress inetAddress = inetAddresses.nextElement();
                        if (inetAddress.isSiteLocalAddress()) {
                            treeSet.add(inetAddress.getHostAddress());
                        }
                    }
                }
            }
            return String.join(",", treeSet.stream().toList());
        } catch (Exception e) {
            throw new CommonException("获取IP地址失败！", e);
        }
    }

    public static String getMachineCode() {
        SystemInfo systemInfo = new SystemInfo();
        HardwareAbstractionLayer hal = systemInfo.getHardware();
        ComputerSystem computerSystem = hal.getComputerSystem();
        CentralProcessor processor = hal.getProcessor();
        String cpuSerial = processor.getProcessorIdentifier().getProcessorID();
        String cpuName = processor.getProcessorIdentifier().getName();
        String boardMode = computerSystem.getModel();
        String boardSerial = computerSystem.getSerialNumber();
        return MD5.encode(cpuSerial + cpuName + boardMode + boardSerial);
    }

    public static String getBase64Code() {
        Map<String, Object> data = new HashMap<>();
        data.put("createTime", System.currentTimeMillis());
        data.put("SystemUUUID", getMachineCode());
        return AESUtil.encrypt(GsonUtil.toJson(data));
    }

    public static void main(String[] args) {
        System.out.println(getMachineCode());
    }
}
